package com.tongjie.hotelbooking.controller.merchant;

import com.tongjie.hotelbooking.dto.DtoConverters;
import com.tongjie.hotelbooking.dto.MemberConversationDto;
import com.tongjie.hotelbooking.dto.OrderDto;
import com.tongjie.hotelbooking.http.BaseResponse;
import com.tongjie.hotelbooking.im.conversation.entiry.MemberConversation;
import com.tongjie.hotelbooking.im.conversation.service.MemberConversationService;
import com.tongjie.hotelbooking.order.entity.Order;
import com.tongjie.hotelbooking.order.enums.OrderStatus;
import com.tongjie.hotelbooking.order.enums.SearchDirection;
import com.tongjie.hotelbooking.order.service.OrderConsultingService;
import com.tongjie.hotelbooking.order.service.OrderService;
import com.tongjie.hotelbooking.security.SecurityHelper;
import com.tongjie.hotelbooking.user.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

@RestController
@RequestMapping("/merchant/order")
public class MerchantOrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private OrderConsultingService orderConsultingService;

    @Resource
    private MemberConversationService memberConversationService;

    @GetMapping("/search")
    public BaseResponse<Page<OrderDto>> searchMerchantOrder(@RequestParam(required = false) Long lastId,
                                                            @RequestParam(required = false) SearchDirection searchDirection) {
        Page<OrderDto> data = this.orderService.searchMerchantOrders(lastId, searchDirection).map(DtoConverters::orderDtoConverter);
        return BaseResponse.success(data);
    }

    @GetMapping("/{orderId}")
    public BaseResponse<OrderDto> getOrderById(@PathVariable Long orderId) {
        Order order = this.orderService.getOrderById(orderId);
        OrderDto orderDto = Optional.ofNullable(order).map(DtoConverters::orderDtoDetailConverter).orElseThrow(() -> new RuntimeException("fail to get order"));
        return BaseResponse.success(orderDto);
    }

    @PostMapping("/accept/{orderId}")
    public BaseResponse<MemberConversationDto> acceptOrder(@PathVariable("orderId") Long orderId) {
        Order order = this.orderService.getOrderById(orderId);
        if (order == null) {
            return BaseResponse.fail(400, "订单不存在", null);
        } else if (!OrderStatus.HANDLING.equals(order.getOrderStatus())) {
            return BaseResponse.fail(400, "订单状态错误，可以能被别人接单", null);
        } else if (this.orderConsultingService.countOrderConsultingByOrder(order) >= 3) {
            return BaseResponse.fail(400, "订单状态错误，可以能被别人接单", null);
        } else if (this.orderConsultingService.getOrderConsultingByOrderIdAndMerchantId(orderId, SecurityHelper.getCurrentUserInfo().getId()) != null) {
            return BaseResponse.fail(400, "不可重复接单", null);
        }
        this.orderService.acceptOrder(orderId);
        MemberConversation memberConversation = this.memberConversationService.getCurrentMemberConversationByUsers(
                User.builder().id(SecurityHelper.getCurrentUserInfo().getId()).build(),
                User.builder().id(order.getCreateUser().getId()).build()
        );
        if (memberConversation == null) {
            return BaseResponse.fail("找不到会话");
        }
        return BaseResponse.success(Optional.ofNullable(memberConversation).map(DtoConverters::memberConversationToMemberConversationDto).get());
    }

    @GetMapping("/find")
    public BaseResponse<Page<OrderDto>> findOrder(
            @RequestParam(required = false) Long lastId,
            @RequestParam(required = false) SearchDirection searchDirection) {
        if (lastId != null && searchDirection == null) {
            return BaseResponse.fail("search direction cat not be null");
        }
        Page<OrderDto> result = this.orderService.findMerchantOrders(lastId, searchDirection).map(DtoConverters::orderDtoConverter);
        return BaseResponse.success(result);
    }


}
